import { ipcMain } from "electron";
import * as child_process from "node:child_process";
import { IS_DEV } from "@electron/main/util/env";
import { exec } from "@electron/main/util/sudo-prompt";

ipcMain.handle("cp:spawn", (_, cmd: string, args?: string[]) => {
  return new Promise<string>((resolve, reject) => {
    if (import.meta.env.DEV) {
      console.log("[cp:spawn]", cmd, args);
    }
    const proc = child_process.spawn(cmd, args, { windowsHide: true });
    let output = "";
    let errorOutput = "";
    proc.stdout.on("data", data => {
      output += data.toString();
    });
    proc.stderr.on("data", data => {
      errorOutput += data.toString();
      if (IS_DEV) {
        console.error(data.toString());
      }
    });
    proc.on("exit", () => (errorOutput ? reject(errorOutput) : resolve(output)));
    proc.on("error", err => reject(err.message));
  });
});

ipcMain.handle("cp:sudo", (_, cmd: string, id?: string) => {
  return new Promise<string>((resolve, reject) => {
    exec(
      cmd,
      { name: "Denv" },
      (err, stdout, stderr) => {
        if (err) {
          reject(stderr?.toString());
        } else {
          resolve(stdout?.toString() ?? "");
        }
      },
      id,
    );
  });
});
